package cn.edu.scau.cmi.wujiaxian.exercise11;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class WindowReader extends JFrame implements ActionListener {

	private static final long serialVersionUID = -8930213189512814290L;
	JFileChooser fileDialog; // 文件操作
	JMenuBar menuBar;
	JMenu menu;
	JMenuItem itemSave;
	JMenuItem itemOpen;
	JTextArea textArea;
	BufferedReader in;
	FileReader fileReader;
	BufferedWriter out;
	FileWriter fileWriter;

	public WindowReader() {
		init();
		setSize(300, 400);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	void init() {
		textArea = new JTextArea(10, 10);
		textArea.setFont(new Font("楷体_gb2312", Font.PLAIN, 28));
		add(new JScrollPane(textArea), BorderLayout.CENTER);
		menuBar = new JMenuBar();
		menu = new JMenu("文件");
		itemSave = new JMenuItem("保存文件");
		itemOpen = new JMenuItem("打开文件");
		itemSave.addActionListener(this);
		itemOpen.addActionListener(this);
		menu.add(itemSave);
		menu.add(itemOpen);
		menuBar.add(menu);
		setJMenuBar(menuBar);
		fileDialog = new JFileChooser();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == itemSave) {
			int state = fileDialog.showSaveDialog(this);
			if (state == JFileChooser.APPROVE_OPTION) {
				try {
					File dir = fileDialog.getCurrentDirectory();
					String name = fileDialog.getSelectedFile().getName();
					File file = new File(dir, name);
					fileWriter = new FileWriter(file);
					out = new BufferedWriter(fileWriter);
					out.write(textArea.getText());
					out.close();
					fileWriter.close();
				} catch (Exception ee) {
				}
			}
		} else if (e.getSource() == itemOpen) {
			int state = fileDialog.showOpenDialog(this);
			if (state == JFileChooser.APPROVE_OPTION) {
				textArea.setText(null);
				try {
					File dir = fileDialog.getCurrentDirectory();
					String name = fileDialog.getSelectedFile().getName();
					File file = new File(dir, name);
					fileReader = new FileReader(file);
					in = new BufferedReader(fileReader);
					String string = null;
					while ((string = in.readLine()) != null) {
						textArea.append(string + "\n");
					}
					in.close();
					fileReader.close();
				} catch (Exception ee) {
				}
			}
		}

	}

}
